<template>
  <div class="video-detail-container">
    <!-- 加载状态 -->
    <div v-if="state.loading" class="loading-wrap">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 内容区域 -->
    <div v-else class="detail-content">
      <!-- 左侧视频区域 -->
      <div class="left-section">
        <div class="player-wrapper">
          <video-player
              class="vjs-custom-skin"
              :options="state.playerOptions"
              @ready="onPlayerReady"
          />
        </div>
      </div>

      <!-- 右侧信息区域 -->
      <div class="right-section">
        <div class="toggle-section">
          <div class="tab-header">
            <div
                class="tab-item"
                :class="{ 'active': state.activeTab === 'intro' }"
                @click="switchTab('intro')"
            >
              简介
            </div>
            <div
                class="tab-item"
                :class="{ 'active': state.activeTab === 'comment' }"
                @click="switchTab('comment')"
            >
              评论 {{ state.comments.length ? `(${state.comments.length})` : '' }}
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="content-box">
            <!-- 简介内容 -->
            <div v-show="state.activeTab === 'intro'" class="intro-content">
              <p class="description">{{ state.videoData.description }}</p>
            </div>

            <!-- 评论内容 -->
            <div v-show="state.activeTab === 'comment'" class="comment-content">
              <div class="comment-section">
                <h2>评论区（{{ state.comments.length }}条）</h2>

                <!-- 评论列表 -->
                <ul class="comment-list">
                  <li
                      v-for="comment in state.comments"
                      :key="comment.id"
                      class="comment-item"
                  >
                    <div class="comment-header">
                      <el-avatar :size="30" :src="comment.avatar" />
                      <div class="user-info">
                        <span class="username">{{ comment.name }}</span>
                        <span class="time">{{ formatTime(comment.createTime) }}</span>
                      </div>
                    </div>
                    <p class="comment-content">{{ comment.content }}</p>

                    <div class="reply-section">
                      <el-button
                          size="small"
                          @click="toggleReply(comment)"
                          class="reply-btn"
                      >
                        {{ comment.showReply ? '取消回复' : '回复' }}
                      </el-button>

                      <!-- 回复表单 -->
                      <div v-if="comment.showReply" class="reply-form">
                        <el-input
                            v-model="state.replyContent"
                            placeholder="写下你的回复..."
                            type="textarea"
                            :rows="2"
                        />
                        <el-button
                            type="primary"
                            size="small"
                            @click="submitReply(comment)"
                            class="submit-btn"
                        >
                          提交回复
                        </el-button>
                      </div>

                      <!-- 回复列表 -->
                      <ul
                          v-if="comment.childCommentList?.length"
                          class="reply-list"
                      >
                        <li
                            v-for="reply in comment.childCommentList"
                            :key="reply.id"
                            class="reply-item"
                        >
                          <div class="comment-header">
                            <el-avatar :size="30" :src="reply.avatar" />
                            <div class="user-info">
                              <span class="username">{{ reply.name }}</span>
                              <span class="time">{{ formatTime(reply.createTime) }}</span>
                            </div>
                          </div>
                          <p class="comment-content">{{ reply.content }}</p>
                        </li>
                      </ul>
                    </div>
                  </li>
                </ul>

                <!-- 新评论表单 -->
                <div class="new-comment">
                  <h3>发表评论</h3>
                  <el-input
                      v-model="state.newComment"
                      placeholder="写下你的评论..."
                      type="textarea"
                      :rows="2"
                  />
                  <el-button
                      style="margin-top: 10px; width: 70px"
                      type="primary"
                      @click="submitComment"
                      class="submit-btn"
                  >
                    提交评论
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import 'video.js/dist/video-js.css'
import { reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { VideoPlayer } from '@videojs-player/vue'
import { getVideoDetail } from '../../service/videoApi.js'
import { ClientAddComment, ClientReplyComment, ClientlistcommentInfo } from '../../service/commentinfoApi.js'

const route = useRoute()

const state = reactive({
  loading: true,
  activeTab: 'intro',
  videoData: {},
  comments: [],
  newComment: '',
  replyContent: '',
  playerOptions: {
    autoplay: false,
    controls: true,
    fluid: true,
    preload: 'auto',
    techOrder: ['html5'],
    sources: []
  }
})

// Initialize player source
const updatePlayerSource = () => {
  state.playerOptions.sources = [{
    src: state.videoData.videoUrl,
    type: getVideoType(state.videoData.videoUrl)
  }];
}

const getVideoType = (url) => {
  const ext = url.split('.').pop().toLowerCase();
  switch (ext) {
    case 'mp4':
      return 'video/mp4';
    case 'webm':
      return 'video/webm';
    default:
      return 'video/mp4';
  }
}

// Fetch video detail
const fetchVideoDetail = async () => {
  try {
    const res = await getVideoDetail(route.params.id)
    state.videoData = res.data
    updatePlayerSource()
  } catch (error) {
    console.error('Failed to fetch video detail:', error)
  } finally {
    state.loading = false
  }
}

// Switch tab
const switchTab = (tabName) => {
  state.activeTab = tabName
  if (tabName === 'comment' && state.comments.length === 0) {
    getComments()
  }
}

// Get comments
const getComments = async () => {
  try {
    const res = await ClientlistcommentInfo(route.params.id)
    state.comments = res.data.map(c => ({ ...c, showReply: false }))
  } catch (error) {
    console.error('Failed to fetch comments:', error)
  }
}

// Submit comment
const submitComment = async () => {
  if (!state.newComment.trim()) {
    ElMessage.warning('Please enter comment content')
    return
  }
  const params = {
    content: state.newComment,
    module: "video",
    rootId: route.params.id,
    relatedId: '0'
  }
  const res = await ClientAddComment(params)
  state.newComment = ''
  ElMessage.success(res.msg)
  await getComments()
}

// Submit reply
const submitReply = async (comment) => {
  if (!state.replyContent.trim()) {
    ElMessage.warning('Please enter reply content')
    return
  }
  const params = {
    content: state.replyContent,
    module: "video",
    parentId: comment.id,
    rootId: route.params.id,
    relatedId: '0'
  }
  const res = await ClientReplyComment(params)
  comment.showReply = false
  state.replyContent = ''
  ElMessage.success(res.msg)
  await getComments()
}

// Toggle reply form
const toggleReply = (comment) => {
  comment.showReply = !comment.showReply
}

// Format time
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// Player ready callback
const onPlayerReady = (player) => {
  console.log('Player is ready');
  const videoElement = player.tech().el();
  videoElement.addEventListener('loadedmetadata', () => {
    console.log('Video metadata loaded', videoElement.videoWidth, videoElement.videoHeight);
  });
}

onMounted(() => {
  fetchVideoDetail()
})
</script>

<style scoped>
.video-detail-container {
  max-width: 1400px;
  width: 100%;
  margin: 20px auto;
}

.detail-content {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.left-section {
  flex: 3;
  display: flex;
  flex-direction: column;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

.player-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* Maintains 16:9 aspect ratio */
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.video-js) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

:deep(.vjs-tech) {
  object-fit: contain;
}

.right-section {
  flex: 1;
  min-width: 400px;
  display: flex;
  flex-direction: column;
  height: auto;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
}

.tab-item {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 15px;
  color: #666;
  position: relative;
  transition: all 0.3s;
}

.tab-item.active {
  color: #409eff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #409eff;
}

.comment-section {
  margin-top: 20px;
}

.comment-section h2 {
  font-size: 16px;
  margin-bottom: 12px;
  color: #333;
}

.comment-list {
  list-style: none;
  padding: 0;
}

.comment-item {
  padding: 2px 0;
  border-bottom: 1px solid #eee;
}

.reply-section {
  margin-top: 12px;
  margin-left: 30px;
}

.reply-form {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.new-comment {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 992px) {
  .detail-content {
    flex-direction: column;
    height: auto;
  }

  .left-section,
  .right-section {
    width: 100%;
    min-width: auto;
  }

  .player-wrapper {
    padding-bottom: 56.25%; /* Maintain aspect ratio */
  }
}

.username {
  font-size: 13px;
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 11px;
  color: #999;
}

.user-info {
  margin-left: 2px;
  display: flex;
  flex-direction: column;
}

.comment-content {
  font-size: 13px;
  line-height: 1.5;
  margin: 8px 0;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reply-item .comment-content {
  font-size: 12px;
}

/* Optimize scroll area */
.content-box {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  max-height: calc(80vh - 70px);
}

.comment-list {
  max-height: 30.5vh;
  overflow-y: auto;
  padding-right: 6px;
}

/* Scrollbar beautification */
.comment-list::-webkit-scrollbar {
  width: 6px;
}

.comment-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.comment-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.comment-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.new-comment h3 {
  font-size: 14px;
  margin-bottom: 8px;
}
</style>